﻿using DBController;
using RRQMSocket;
using RRQMSocket.FileTransfer;
using RRQMSocket.RPC;
using ServiceLog;
using System;

namespace WeChatService
{
    public class Service
    {
        private static FileService fileService;
        private static RRQMRPCService rPCService;

        /// <summary>
        /// 开启服务器
        /// </summary>
        /// <returns></returns>
        public static void OpenService()
        {
            try
            {
                if (fileService != null || rPCService != null)
                {
                    MainLog.WriteLog("请先关闭服务器再重新开启");
                    return;
                }
                fileService = new FileService();

                BindSetting bindSetting = new BindSetting();
                bindSetting.IP = Controller.AppConfig.ServiceIP;
                bindSetting.Port = Controller.AppConfig.FileServicePort;
                bindSetting.MultithreadThreadCount = Controller.AppConfig.FileServiceThreadCount;
                fileService.Bind(bindSetting);
                fileService.Logger = new RRQMSocketLog();

                rPCService = new RRQMRPCService();
                bindSetting.Port = Controller.AppConfig.RPCServicePort;
                bindSetting.MultithreadThreadCount = Controller.AppConfig.RPCServiceThreadCount;
                rPCService.Bind(bindSetting);

                RPCServerSetting serverSetting = new RPCServerSetting();
                serverSetting.NameSpace = "RRQMWeChat";
                serverSetting.RPCServerMode = RPCServerMode.Senior;
                rPCService.OpenRPCServer(serverSetting);
                rPCService.SerializeConverter = new RRQMSocket_SerializeConverter.JsonTSerializeConverter();

                MainLog.WriteLog("服务器启动成功");
                return;
            }
            catch (Exception e)
            {
                MainLog.WriteLog(e.Message);
                return;
            }
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        public static void CloseService()
        {
            if (fileService != null)
            {
                fileService.Dispose();
                fileService = null;
            }

            if (rPCService != null)
            {
                rPCService.Dispose();
                rPCService = null;
            }
        }
    }
}